<?php

import('@.Org.GoodsTool');
import('@.Org.BaseTool');


/**
 * 更新用户SESSION,COOKIE及登录时间、登录次数。
 *
 * @access  public
 * @return  void
 */
function update_user_info(){
    if (!$_SESSION['user_id']){
        return false;
    }
	
    $CommonModel	=	new CommonModel();
    
    /* 查询会员信息 */
    $time 			= 	date('Y-m-d');
    $sql 			= 	'SELECT u.user_money,u.email, u.pay_points, u.user_rank, u.rank_points, '.
            			' IFNULL(b.type_money, 0) AS user_bonus, u.last_login, u.last_ip'.
            			' FROM ' . 'ybr_users' . ' AS u ' .
            			' LEFT JOIN ' .'ybr_user_bonus' . ' AS ub'.
            			' ON ub.user_id = u.user_id AND ub.used_time = 0 ' .
            			' LEFT JOIN ' .'ybr_bonus_type' . ' AS b'.
            			" ON b.type_id = ub.bonus_type_id AND b.use_start_date <= '$time' AND b.use_end_date >= '$time' ".
            			" WHERE u.user_id = '$_SESSION[user_id]'";
    
    if ($row = $CommonModel->getRow($sql)){
        /* 更新SESSION */
        $_SESSION['last_time']   	= 	$row['last_login'];
        $_SESSION['last_ip']     	= 	$row['last_ip'];
        $_SESSION['login_fail']  	= 	0;
        $_SESSION['email']       	=	$row['email'];

        /*判断是否是特殊等级，可能后台把特殊会员组更改普通会员组*/
        if($row['user_rank'] >0){
            $sql					=	"SELECT special_rank from ".'ybr_user_rank' . "where rank_id='$row[user_rank]'";
            
            if( $CommonModel->getOne($sql)==='0' || $CommonModel->getOne($sql)===null ){   
                $sql				=	"update ".'ybr_users' . "set user_rank='0' where user_id='$_SESSION[user_id]'";
                
                $CommonModel->query($sql);
                $row['user_rank']	=	0;
            }
        }

        /* 取得用户等级和折扣 */
        if ($row['user_rank'] == 0){
            // 非特殊等级，根据等级积分计算用户等级（注意：不包括特殊等级）
            $sql 					= 	'SELECT rank_id, discount FROM ' . 'ybr_user_rank' . " WHERE special_rank = '0' AND min_points <= " . intval($row['rank_points']) . ' AND max_points > ' . intval($row['rank_points']);
            if ($row = $CommonModel->getRow($sql)){
                $_SESSION['user_rank'] 	= 	$row['rank_id'];
                $_SESSION['discount']  	= 	$row['discount'] / 100.00;
            }
            else{
                $_SESSION['user_rank'] 	=	0;
                $_SESSION['discount']  	= 	1;
            }
        }
        else{
            // 特殊等级
            $sql 						= 	'SELECT rank_id, discount FROM ' . 'ybr_user_rank' . " WHERE rank_id = '$row[user_rank]'";
            if ($row = $CommonModel->getRow($sql)){
                $_SESSION['user_rank']	= 	$row['rank_id'];
                $_SESSION['discount']  	= 	$row['discount'] / 100.00;
            }
            else{
                $_SESSION['user_rank'] 	= 	0;
                $_SESSION['discount']  	= 	1;
            }
        }
    }

    /* 更新登录时间，登录次数及登录ip */
    $sql 								= 	"UPDATE " .'ybr_users' . " SET".
								           	" visit_count = visit_count + 1, ".
								           	" last_ip = '" .real_ip(). "',".
								           	" last_login = '" .gmtime(). "'".
								           	" WHERE user_id = '" . $_SESSION['user_id'] . "'";
    $CommonModel->query($sql);
}


/**
 * 重新计算购物车中的商品价格：目的是当用户登录时享受会员价格，当用户退出登录时不享受会员价格
 * 如果商品有促销，价格不变
 *
 * @access  public
 * @return  void
 */
function recalculate_price(){
	$CommonModel	=	new CommonModel();
    /* 取得有可能改变价格的商品：除配件和赠品之外的商品 */
    $sql 				= 	'SELECT c.rec_id, c.goods_id, c.goods_attr_id, g.promote_price, g.promote_start_date, c.goods_number,'.
	                		"g.promote_end_date, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS member_price ".
				            'FROM ' . 'ybr_cart' . ' AS c '.
				            'LEFT JOIN ' . 'ybr_goods' . ' AS g ON g.goods_id = c.goods_id '.
				            "LEFT JOIN " . 'ybr_member_price' . " AS mp ".
				                    "ON mp.goods_id = g.goods_id AND mp.user_rank = '" . $_SESSION['user_rank'] . "' ".
				            "WHERE session_id = '" .SESS_ID. "' AND c.parent_id = 0 AND c.is_gift = 0 AND c.goods_id > 0 " .
				            "AND c.rec_type = '" . CART_GENERAL_GOODS . "' AND c.extension_code <> 'package_buy'";

            $res 		= 	$CommonModel->query($sql);

    foreach ($res AS $row){
        $attr_id    	= 	empty($row['goods_attr_id']) ? array() : explode(',', $row['goods_attr_id']);
        
        $goods_price 	= 	get_final_price($row['goods_id'], $row['goods_number'], true, $attr_id);


        $goods_sql 		= 	"UPDATE " .'ybr_cart' . " SET goods_price = '$goods_price' ".
                     		"WHERE goods_id = '" . $row['goods_id'] . "' AND session_id = '" . SESS_ID . "' AND rec_id = '" . $row['rec_id'] . "'";

        $CommonModel->query($goods_sql);
    }

    /* 删除赠品，重新选择 */
   $CommonModel->query('DELETE FROM ' . 'ybr_cart' . " WHERE session_id = '" . SESS_ID . "' AND is_gift > 0");
}


/**
 * 取得用户等级信息
 * @access   public
 * @author   Xuan Yan
 *
 * @return array
 */
function get_rank_info(){
    
	$CommonModel		=	new CommonModel();

    if (!empty($_SESSION['user_rank'])){
        $sql 			= 	"SELECT rank_name, special_rank FROM " . 'ybr_user_rank' . " WHERE rank_id = '$_SESSION[user_rank]'";
        $row 			= 	$CommonModel->getRow($sql);
        if (empty($row)){
            return array();
        }
        $rank_name 		= 	$row['rank_name'];
        if ($row['special_rank']){
            return array('rank_name'=>$rank_name);
        }
        else{
            $user_rank 		= 	$CommonModel->getOne("SELECT rank_points FROM " . 'ybr_users' . " WHERE user_id = '$_SESSION[user_id]'");
            $sql 			= 	"SELECT rank_name,min_points FROM " . 'ybr_user_rank' . " WHERE min_points > '$user_rank' ORDER BY min_points ASC LIMIT 1";
            $rt  			= 	$CommonModel->getRow($sql);
            $next_rank_name = 	$rt['rank_name'];
            $next_rank 		= 	$rt['min_points'] - $user_rank;
            
            return array('rank_name'=>$rank_name,'next_rank_name'=>$next_rank_name,'next_rank'=>$next_rank);
        }
    }
    else{
        return array();
    }
}

/**
 * 获取用户中心默认页面所需的数据
 *
 * @access  public
 * @param   int         $user_id            用户ID
 *
 * @return  array       $info               默认页面所需资料数组
 */
function get_user_default($user_id){
	
	$ComonModel				=	new CommonModel();
	
    $user_bonus 			= 	get_user_bonus();

    $sql 					= 	"SELECT pay_points, user_money, credit_line, last_login, is_validated FROM " .'ybr_users' . " WHERE user_id = '$user_id'";
    $row 					= 	$ComonModel->getRow($sql);
    $info 					= 	array();
    $info['username']  		= 	stripslashes($_SESSION['user_name']);
    $info['shop_name'] 		= 	$GLOBALS['_CFG']['shop_name'];
    $info['integral']  		= 	$row['pay_points'] . $GLOBALS['_CFG']['integral_name'];
    /* 增加是否开启会员邮件验证开关 */
    //$info['is_validate'] 	= 	($GLOBALS['_CFG']['member_email_validate'] && !$row['is_validated']) ? 0 : 1;
    $info['is_validate'] 	= 	$row['is_validated'] ? 0 : 1;
    $info['credit_line'] 	= 	$row['credit_line'];
    $info['formated_credit_line'] 	= 	price_format($info['credit_line'], false);

    //如果$_SESSION中时间无效说明用户是第一次登录。取当前登录时间。
    $last_time 				= 	!isset($_SESSION['last_time']) ? $row['last_login'] : $_SESSION['last_time'];

    if ($last_time == 0){
        $_SESSION['last_time'] 	= 	$last_time 	= 	gmtime();
    }

    $info['last_time'] 		= 	local_date($GLOBALS['_CFG']['time_format'], $last_time);
    $info['surplus']   		= 	price_format($row['user_money'], false);
    $info['bonus']     		= 	sprintf($GLOBALS['_LANG']['user_bonus_info'], $user_bonus['bonus_count'], price_format($user_bonus['bonus_value'], false));

    $sql 					= 	"SELECT COUNT(*) FROM " .'ybr_order_info' .
            					" WHERE user_id = '" .$user_id. "' AND add_time > '" .local_strtotime('-1 months'). "'";
    $info['order_count'] 	= 	$ComonModel->getOne($sql);

    $sql 					= 	"SELECT order_id, order_sn ".
            					" FROM " .'ybr_order_info' .
            					" WHERE user_id = '" .$user_id. "' AND shipping_time > '" .$last_time. "'". order_query_sql('shipped');
    $info['shipped_order'] 	= 	$ComonModel->query($sql);

    return $info;
}


/**
 *  获取用户参与活动信息
 *
 * @access  public
 * @param   int     $user_id        用户id
 *
 * @return  array
 */
function get_user_prompt ($user_id){
	
	$CommonModel		=	new CommonModel();
	
    $prompt 			= 	array();
    $now 				= 	gmtime();
    /* 夺宝奇兵 */
    $sql 				= 	"SELECT act_id, goods_name, end_time " .
				            "FROM " . 'ybr_goods_activity' .
				            " WHERE act_type = '" . GAT_SNATCH . "'" .
				            " AND (is_finished = 1 OR (is_finished = 0 AND end_time <= '$now'))";
    $res 				= 	$CommonModel->query($sql);
    
    foreach($res as $row){
     	$act_id 		= 	$row['act_id'];
        $result 		= 	get_snatch_result($act_id);
        if (isset($result['order_count']) && $result['order_count'] == 0 && $result['user_id'] == $user_id){
            $prompt[] = array(
                   'text'		=> sprintf( L('your_snatch'),$row['goods_name'], $row['act_id']),
                   'add_time'	=> $row['end_time']
            );
        }
        if (isset($auction['last_bid']) && $auction['last_bid']['bid_user'] == $user_id && $auction['order_count'] == 0){
            $prompt[] = array(
                'text' 		=> sprintf( L('your_auction'), $row['goods_name'], $row['act_id']),
                'add_time' 	=> $row['end_time']
            );
        }
    }

    /* 竞拍 */

    $sql 					= 	"SELECT act_id, goods_name, end_time " .
					            "FROM " . 'ybr_goods_activity' .
					            " WHERE act_type = '" . GAT_AUCTION . "'" .
					            " AND (is_finished = 1 OR (is_finished = 0 AND end_time <= '$now'))";
    $res 					= 	$CommonModel->query($sql);
    
    foreach($res as $row){
    	$act_id 			=	$row['act_id'];
        $auction 			= 	auction_info($act_id);
        if (isset($auction['last_bid']) && $auction['last_bid']['bid_user'] == $user_id && $auction['order_count'] == 0){
            $prompt[] = array(
                'text' => sprintf($GLOBALS['_LANG']['your_auction'], $row['goods_name'], $row['act_id']),
                'add_time' => $row['end_time']
            );
        }
    }

    /* 排序 */
    $cmp = create_function('$a, $b', 'if($a["add_time"] == $b["add_time"]){return 0;};return $a["add_time"] < $b["add_time"] ? 1 : -1;');
    usort($prompt, $cmp);

    /* 格式化时间 */
    foreach ($prompt as $key => $val)
    {
        $prompt[$key]['formated_time'] = local_date($GLOBALS['_CFG']['time_format'], $val['add_time']);
    }

    return $prompt;
}



/**
 * 获取用户帐号信息
 *
 * @access  public
 * @param   int       $user_id        用户user_id
 *
 * @return void
 */
function get_profile($user_id){	
    Vendor('Integrates.ecshop');    
    $User				=	new Ecshop();
    $GLOBALS['ecs']		=	& $User;
	
    $CommonModel		=	new CommonModel();

    /* 会员帐号信息 */
    $info  				= 	array();
    $infos 				= 	array();
    $sql  				= 	"SELECT user_name, birthday, sex, question, answer, rank_points, pay_points,user_money, user_rank,".
				            " msn, qq, office_phone, home_phone, mobile_phone, passwd_question, passwd_answer ".
				            "FROM " . 'ybr_users' . " WHERE user_id = '$user_id'";
    $infos 				= 	$CommonModel->getRow($sql);
    $infos['user_name'] = 	addslashes($infos['user_name']);

    $row 				= 	$User->get_profile_by_name($infos['user_name']); //获取用户帐号信息
    $_SESSION['email'] 	= 	$row['email'];    //注册SESSION

    /* 会员等级 */
    if ($infos['user_rank'] > 0){
        $sql 			= 	"SELECT rank_id, rank_name, discount FROM ". 'ybr_user_rank' .
               				" WHERE rank_id = '$infos[user_rank]'";
    }
    else{
        $sql 			= 	"SELECT rank_id, rank_name, discount, min_points".
			               	" FROM ". 'ybr_user_rank' .
			               	" WHERE min_points<= " . intval($infos['rank_points']) . " ORDER BY min_points DESC";
	}
	
    if ($row = $CommonModel->getRow($sql)){
        $info['rank_name']     	= 	$row['rank_name'];
    }
    else{
        $info['rank_name'] 		= 	$GLOBALS['_LANG']['undifine_rank'];
    }

    $cur_date 					= 	date('Y-m-d H:i:s');

    /* 会员红包 */
    $bonus 						= 	array();
    $sql 						= 	"SELECT type_name, type_money ".
						           	"FROM " . 'ybr_bonus_type' . " AS t1, " . 'ybr_user_bonus' . " AS t2 ".
						           	"WHERE t1.type_id = t2.bonus_type_id AND t2.user_id = '$user_id' AND t1.use_start_date <= '$cur_date' ".
						           	"AND t1.use_end_date > '$cur_date' AND t2.order_id = 0";
    $bonus 						= 	$CommonModel->query($sql);
    if ($bonus){
        for ($i = 0, $count = count($bonus); $i < $count; $i++){
            $bonus[$i]['type_money'] 	= 	price_format($bonus[$i]['type_money'], false);
        }
    }

    $info['discount']    		= 	$_SESSION['discount'] * 100 . "%";
    $info['email']       		= 	$_SESSION['email'];
    $info['user_name']   		= 	$_SESSION['user_name'];
    $info['rank_points'] 		= 	isset($infos['rank_points']) ? $infos['rank_points'] : '';
    $info['pay_points']  		= 	isset($infos['pay_points'])  ? $infos['pay_points']  : 0;
    $info['user_money']  		= 	isset($infos['user_money'])  ? $infos['user_money']  : 0;
    $info['sex']         		= 	isset($infos['sex'])      ? $infos['sex']      : 0;
    $info['birthday']    		= 	isset($infos['birthday']) ? $infos['birthday'] : '';
    $info['question']    		= 	isset($infos['question']) ? htmlspecialchars($infos['question']) : '';

    $info['user_money']  		= 	price_format($info['user_money'], false);
    $info['pay_points']  		= 	$info['pay_points'] . $GLOBALS['_CFG']['integral_name'];
    $info['bonus']       		= 	$bonus;
    $info['qq']          		= 	$infos['qq'];
    $info['msn']          		= 	$infos['msn'];
    $info['office_phone']		= 	$infos['office_phone'];
    $info['home_phone']   		= 	$infos['home_phone'];
    $info['mobile_phone'] 		= 	$infos['mobile_phone'];
    $info['passwd_question'] 	= 	$infos['passwd_question'];
    $info['passwd_answer'] 		= 	$infos['passwd_answer'];

    return $info;
}

/**
 *  获取用户指定范围的订单列表
 *
 * @access  public
 * @param   int         $user_id        用户ID号
 * @param   int         $num            列表最大数量
 * @param   int         $start          列表起始位置
 * @return  array       $order_list     订单列表
 */
function get_user_orders($user_id, $num = 10, $start = 0){
	
	$CommonModel		=	new CommonModel();
    /* 取得订单列表 */
    $arr    			= 	array();

    $sql 				= 	"SELECT order_id, order_sn, order_status, shipping_status, pay_status, add_time, " .
				           	"(goods_amount + shipping_fee + insure_fee + pay_fee + pack_fee + card_fee + tax - discount) AS total_fee ".
				           	" FROM " .'ybr_order_info'  .
				           	" WHERE user_id = '$user_id' ORDER BY add_time DESC";
    
    $res 				= 	$CommonModel->query($sql);
	
    foreach($res as $row){
    	if ($row['order_status'] == OS_UNCONFIRMED){
            //$row['handler'] = "<a href=\"user.php?act=cancel_order&order_id=" .$row['order_id']. "\" onclick=\"if (!confirm('".$GLOBALS['_LANG']['confirm_cancel']."')) return false;\">".$GLOBALS['_LANG']['cancel']."</a>";
            $row['handler'] = "<a href=\"" . U('user/cancel_order') . "?order_id=" .$row['order_id']. "\" onclick=\"if (!confirm('".$GLOBALS['_LANG']['confirm_cancel']."')) return false;\">".$GLOBALS['_LANG']['cancel']."</a>";
        }
        else if ($row['order_status'] == OS_SPLITED){
            /* 对配送状态的处理 */
            if ($row['shipping_status'] == SS_SHIPPED){
                @$row['handler'] = "<a href=\"user.php?act=affirm_received&order_id=" .$row['order_id']. "\" onclick=\"if (!confirm('".$GLOBALS['_LANG']['confirm_received']."')) return false;\">".$GLOBALS['_LANG']['received']."</a>";
            }
            elseif ($row['shipping_status'] == SS_RECEIVED){
                @$row['handler'] = '<span style="color:red">'.$GLOBALS['_LANG']['ss_received'] .'</span>';
            }
            else{
                if ($row['pay_status'] == PS_UNPAYED){
                    @$row['handler'] 	= 	"<a href=\"user.php?act=order_detail&order_id=" .$row['order_id']. '">' .$GLOBALS['_LANG']['pay_money']. '</a>';
                }
                else{
                    @$row['handler'] = "<a href=\"user.php?act=order_detail&order_id=" .$row['order_id']. '">' .$GLOBALS['_LANG']['view_order']. '</a>';
                }
            }
        }
        else{
            $row['handler'] 		= 	'<span style="color:red">'.$GLOBALS['_LANG']['os'][$row['order_status']] .'</span>';
        }

        $row['shipping_status'] 	= 	($row['shipping_status'] == SS_SHIPPED_ING) ? SS_PREPARING : $row['shipping_status'];
        $row['order_status'] 		= 	$GLOBALS['_LANG']['os'][$row['order_status']] . ',' . $GLOBALS['_LANG']['ps'][$row['pay_status']] . ',' . $GLOBALS['_LANG']['ss'][$row['shipping_status']];

        $arr[] = array('order_id'       => $row['order_id'],
                       'order_sn'       => $row['order_sn'],
                       'order_time'     => local_date($GLOBALS['_CFG']['time_format'], $row['add_time']),
                       'order_status'   => $row['order_status'],
                       'total_fee'      => price_format($row['total_fee'], false),
                       'handler'        => $row['handler']);
    }

    return $arr;
}


/**
 *  获取用户可以和并的订单数组
 *
 * @access  public
 * @param   int         $user_id        用户ID
 *
 * @return  array       $merge          可合并订单数组
 */
function get_user_merge($user_id){
	
	$CommonModel		=	new CommonModel();
		
    $sql  				= 	"SELECT order_sn FROM " . 'ybr_order_info' .
            				" WHERE user_id  = '$user_id' " . order_query_sql('unprocessed') .
                			"AND extension_code = '' ".
            				" ORDER BY add_time DESC";
    $list 				= 	$CommonModel->getCol($sql);
    $merge 				= 	array();
    foreach ($list as $val){
        $merge[$val] = $val; 
    }
    return $merge;
}

/**
 * 取得收货人地址列表
 * @param   int     $user_id    用户编号
 * @return  array
 */
function get_consignee_list($user_id){
    $sql 	= 	"SELECT * FROM  `ybr_user_address`  WHERE user_id = '$user_id' ";//LIMIT 5";
    return M()->query($sql);
}


/**
 *  获取指定用户的留言
 *
 * @access  public
 * @param   int     $user_id        用户ID
 * @param   int     $user_name      用户名
 * @param   int     $num            列表最大数量
 * @param   int     $start          列表其实位置
 * @return  array   $msg            留言及回复列表
 * @return  string  $order_id       订单ID
 */
function get_message_list($user_id, $user_name, $order_id = 0){
	
	$CommonModel		=	new CommonModel();
    /* 获取留言数据 */
    $msg 				= 	array();
    $sql 				= 	"SELECT * FROM " . 'ybr_feedback';
    if ($order_id){
        $sql 			.=	" WHERE parent_id = 0 AND order_id = '$order_id' AND user_id = '$user_id' ORDER BY msg_time DESC";
    }
    else{
        $sql .= " WHERE parent_id = 0 AND user_id = '$user_id' AND user_name = '" . $_SESSION['user_name'] . "' AND order_id=0 ORDER BY msg_time DESC";
    }

    $res 				= 	$CommonModel->query($sql);
	
    foreach($res as $rows){
    	 /* 取得留言的回复 */
      	$reply 			= 	array();
		$sql   			= 	"SELECT user_name, user_email, msg_time, msg_content".
							" FROM " .'ybr_feedback' .
							" WHERE parent_id = '" . $rows['msg_id'] . "'";
		$reply 			= 	$CommonModel->getRow($sql);
	
		if ($reply){
			$msg[$rows['msg_id']]['re_user_name']   	= 	$reply['user_name'];
			$msg[$rows['msg_id']]['re_user_email']  	= 	$reply['user_email'];
			$msg[$rows['msg_id']]['re_msg_time']    	= 	local_date($GLOBALS['_CFG']['time_format'], $reply['msg_time']);
			$msg[$rows['msg_id']]['re_msg_content'] 	= 	nl2br(htmlspecialchars($reply['msg_content']));
		}

        $msg[$rows['msg_id']]['msg_content'] = nl2br(htmlspecialchars($rows['msg_content']));
        $msg[$rows['msg_id']]['msg_time']    = local_date($GLOBALS['_CFG']['time_format'], $rows['msg_time']);
        $msg[$rows['msg_id']]['msg_type']    = $order_id ? $rows['user_name'] : $GLOBALS['_LANG']['type'][$rows['msg_type']];
        $msg[$rows['msg_id']]['msg_title']   = nl2br(htmlspecialchars($rows['msg_title']));
        $msg[$rows['msg_id']]['message_img'] = $rows['message_img'];
        $msg[$rows['msg_id']]['order_id'] = $rows['order_id'];
    }
    return $msg;
}



/**
 *
 * @access  public
 * @param   int         $user_id         用户ID
 * @param   int         $num             列表显示条数
 * @param   int         $start           显示起始位置
 *
 * @return  array       $arr             红保列表
 */
function get_user_bouns_list($user_id, $num = 10, $start = 0){
	
	$CommonModel	=	new CommonModel();
	
    $sql 			= 	"SELECT u.bonus_sn, u.order_id, b.type_name, b.type_money, b.min_goods_amount, b.use_start_date, b.use_end_date ".
           				" FROM " . 'ybr_user_bonus' . " AS u ,".
           				'ybr_bonus_type' . " AS b".
           				" WHERE u.bonus_type_id = b.type_id AND u.user_id = '" .$user_id. "'";
    $res 			= 	$CommonModel->query($sql);
    
    $arr 			= 	array();
    $day 			= 	getdate();
    $cur_date 		= 	local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

    foreach($res as $row){
    	/* 先判断是否被使用，然后判断是否开始或过期 */
        if (empty($row['order_id'])){
            /* 没有被使用 */
            if ($row['use_start_date'] > $cur_date){
                $row['status'] 		= 	$GLOBALS['_LANG']['not_start'];
            }
            else if ($row['use_end_date'] < $cur_date){
                $row['status'] 		= 	$GLOBALS['_LANG']['overdue'];
            }
            else{
                $row['status'] 		= 	$GLOBALS['_LANG']['not_use'];
            }
        }
        else{
            $row['status'] 			= 	'<a href="user.php?act=order_detail&order_id=' .$row['order_id']. '" >' .$GLOBALS['_LANG']['had_use']. '</a>';
        }

        $row['use_startdate']   	= 	local_date($GLOBALS['_CFG']['date_format'], $row['use_start_date']);
        $row['use_enddate']     	= 	local_date($GLOBALS['_CFG']['date_format'], $row['use_end_date']);

        $arr[] = $row;	
    }
    return $arr;
}


/**
 *  获取用户评论
 *
 * @access  public
 * @param   int     $user_id        用户id
 * @param   int     $page_size      列表最大数量
 * @param   int     $start          列表起始页
 * @return  array
 */
function get_comment_list($user_id, $page_size, $start){
	
	$CommonModel	=	new CommonModel();
	
    $sql 			= 	"SELECT c.*, g.goods_name AS cmt_name, r.content AS reply_content, r.add_time AS reply_time ".
			           	" FROM " . 'ybr_comment' . " AS c ".
			           	" LEFT JOIN " . 'ybr_comment' . " AS r ".
			           	" ON r.parent_id = c.comment_id AND r.parent_id > 0 ".
			           	" LEFT JOIN " . 'ybr_goods' . " AS g ".
			           	" ON c.comment_type=0 AND c.id_value = g.goods_id ".
			           	" WHERE c.user_id='$user_id'";
    $res 			= 	$CommonModel->query($sql);

    $comments 		= 	array();
    $to_article 	= 	array();
    
    foreach ($res as $row) {
    	$row['formated_add_time'] 		= 	local_date($GLOBALS['_CFG']['time_format'], $row['add_time']);
        if ($row['reply_time']){
            $row['formated_reply_time'] = 	local_date($GLOBALS['_CFG']['time_format'], $row['reply_time']);
        }
        if ($row['comment_type'] == 1){
            $to_article[] 				=	$row["id_value"];
        }
        $comments[] 					= 	$row;
    }

    if ($to_article){
        $sql 			= 	"SELECT article_id , title FROM " . 'ybr_article' . " WHERE " . db_create_in($to_article, 'article_id');
        $arr 			= 	$CommonModel->query($sql);
        $to_cmt_name = array();
        foreach ($arr as $row){
            $to_cmt_name[$row['article_id']] 	= 	$row['title'];
        }

        foreach ($comments as $key=>$row){
            if ($row['comment_type'] == 1){
                $comments[$key]['cmt_name'] 	= 	isset($to_cmt_name[$row['id_value']]) ? $to_cmt_name[$row['id_value']] : '';
            }
        }
    }

    return $comments;
}



/**
 * 查询会员余额的数量
 * @access  public
 * @param   int     $user_id        会员ID
 * @return  int
 */
function get_user_surplus($user_id){	
	$CommonModel	=	new CommonModel();	
    $sql 			= 	"SELECT SUM(user_money) FROM " . 'ybr_account_log' .
           				" WHERE user_id = '$user_id'";
    return $CommonModel->getOne($sql);
}


/**
 * 查询会员余额的操作记录
 *
 * @access  public
 * @param   int     $user_id    会员ID
 * @param   int     $num        每页显示数量
 * @param   int     $start      开始显示的条数
 * @return  array
 */
function get_account_log($user_id, $num, $start){
	$CommonModel			=	new CommonModel();
	
    $account_log 			= 	array();
    $sql 					= 	'SELECT * FROM ' . 'ybr_user_account' .
						        " WHERE user_id = '$user_id'" .
						        " AND process_type " . db_create_in(array(SURPLUS_SAVE, SURPLUS_RETURN)) .
						        " ORDER BY add_time DESC";
    $res 					= 	$CommonModel->query($sql);

    if ($res){
    	foreach($res as $rows){
    		$rows['add_time']         	= 	local_date($GLOBALS['_CFG']['date_format'], $rows['add_time']);
            $rows['admin_note']      	= 	nl2br(htmlspecialchars($rows['admin_note']));
            $rows['short_admin_note'] 	= 	($rows['admin_note'] > '') ? sub_str($rows['admin_note'], 30) : 'N/A';
            $rows['user_note']        	= 	nl2br(htmlspecialchars($rows['user_note']));
            $rows['short_user_note']  	= 	($rows['user_note'] > '') ? sub_str($rows['user_note'], 30) : 'N/A';
            $rows['pay_status']       	= 	($rows['is_paid'] == 0) ? $GLOBALS['_LANG']['un_confirm'] : $GLOBALS['_LANG']['is_confirm'];
            $rows['amount']           	= 	price_format(abs($rows['amount']), false);

            /* 会员的操作类型： 冲值，提现 */
            if ($rows['process_type'] == 0){
                $rows['type'] 			= 	$GLOBALS['_LANG']['surplus_type_0'];
            }
            else{
                $rows['type'] 			= 	$GLOBALS['_LANG']['surplus_type_1'];
            }

            /* 支付方式的ID */
            $sql 						= 	'SELECT pay_id FROM ' .'ybr_payment' .
                   							" WHERE pay_name = '$rows[payment]' AND enabled = 1";
            $pid 						= 	$CommonModel->getOne($sql);

            /* 如果是预付款而且还没有付款, 允许付款 */
            if (($rows['is_paid'] == 0) && ($rows['process_type'] == 0)){
                $rows['handle'] 		= 	'<a href="user.php?act=pay&id='.$rows['id'].'&pid='.$pid.'">'.$GLOBALS['_LANG']['pay'].'</a>';
            }
            $account_log[] 				= 	$rows;
    	}
        return $account_log;
    }
    else{
         return false;
    }
}

/**
 *  给指定用户添加一个指定红包
 *
 * @access  public
 * @param   int         $user_id        用户ID
 * @param   string      $bouns_sn       红包序列号
 *
 * @return  boolen      $result
 */
function add_bonus($user_id, $bouns_sn){
	
	$CommonModel		=	new CommonModel();
	$error_msg			=	array(
		'msg'		=>'操作失败',
		'result'	=>false
	);
	
    if (empty($user_id)){
        $error_msg['msg']		=	$GLOBALS['_LANG']['not_login'];	// 记录错误信息
        $error_msg['result']	=	false;							// 记录操作的结果
        return $error_msg;
    }

    /* 查询红包序列号是否已经存在 */
    $sql 					= 	"SELECT bonus_id, bonus_sn, user_id, bonus_type_id FROM " . 'ybr_user_bonus' .
           						" WHERE bonus_sn = '$bouns_sn'";
    $row 					= 	$CommonModel->getRow($sql);
        
    if ($row){
        if ($row['user_id'] == 0){
            //红包没有被使用
            $sql 			= 	"SELECT send_end_date, use_end_date ".
			                    " FROM " . 'ybr_bonus_type' .
			                   	" WHERE type_id = '" . $row['bonus_type_id'] . "'";

            $bonus_time 	= 	$GLOBALS['db']->getRow($sql);

            $now 			= 	gmtime();
            if ($now > $bonus_time['use_end_date']){
                $error_msg['msg']		=	$GLOBALS['_LANG']['bonus_use_expire'];	// 记录错误信息
                $error_msg['result']	=	false;									// 记录操作的结果
                return $error_msg;
            }

            $sql 			= 	"UPDATE " .'ybr_user_bonus' . " SET user_id = '$user_id' ".
                   				"WHERE bonus_id = '$row[bonus_id]'";
            $result 		= 	$CommonModel->query($sql);
            if ($result){
            	 $error_msg['result']	=	true;							// 记录操作的结果
                 return $error_msg;
            }
            else{
                $error_msg['msg']		=	$CommonModel->getError();
                $error_msg['result']	=	false;
                return $error_msg;
            }
        }
        else{
            if ($row['user_id']== $user_id){
                //红包已经添加过了。
                $error_msg['msg']		=	$GLOBALS['_LANG']['bonus_is_used'];
            }
            else{
                //红包被其他人使用过了。
                $error_msg['msg']		=	$GLOBALS['_LANG']['bonus_is_used_by_other'];
            }
            $error_msg['result']		=	false;
            return $error_msg;
        }
    }
    else{
        //红包不存在
        $error_msg['msg']		=	$GLOBALS['_LANG']['bonus_not_exist'];
        $error_msg['result']	=	false;
        return $error_msg;
    }
}


/**
 * 修改个人资料（Email, 性别，生日)
 *
 * @access  public
 * @param   array       $profile       array_keys(user_id int, email string, sex int, birthday string);
 *
 * @return  boolen      $bool
 */
function edit_profile($profile){	
	Vendor('Integrates.ecshop');
    
    $User				=	new Ecshop();
    $GLOBALS['ecs']		=	& $User;
	
	$CommonModel		=	new CommonModel();
	
	
	$result				=	array(
		'msg'		=>'操作失败',
		'status'	=>false
	);
	
    if (empty($profile['user_id'])){
    	// record error
        $result['msg']		=	$GLOBALS['_LANG']['not_login'];
        $result['status']	=	false;
        return $result;
    }

    $cfg 					= 	array();
    $cfg['username'] 		= 	$CommonModel->getOne("SELECT user_name FROM " . 'ybr_users' . " WHERE user_id='" . $profile['user_id'] . "'");
    /* 性别,邮箱,生日, */
    if (isset($profile['sex'])){
        $cfg['gender'] 		= 	intval($profile['sex']);
    }
    if (!empty($profile['email'])){
        if (!is_email($profile['email'])){
        	// record error
            $result['msg']		=	sprintf($GLOBALS['_LANG']['email_invalid'], $profile['email']);
            $result['status']	=	false;
            return $result;
        }
        $cfg['email'] 			= 	$profile['email'];
    }
    if (!empty($profile['birthday'])){
        $cfg['bday'] 			= 	$profile['birthday'];
    }
	    
    if (!$User->edit_user($cfg)){
        if ($GLOBALS['user']->error == ERR_EMAIL_EXISTS){
            $result['msg']		=	sprintf($GLOBALS['_LANG']['email_exist'], $profile['email']);
        }
        else{
            $result['msg']		=	$CommonModel->getError();
        }
        $result['status']		=	false;
        return $result;
    }

    /* 过滤非法的键值 */
    $other_key_array 			= 	array('msn', 'qq', 'office_phone', 'home_phone', 'mobile_phone');
    foreach ($profile['other'] as $key => $val){
        //删除非法key值
        if (!in_array($key, $other_key_array)){
            unset($profile['other'][$key]);
        }
        else{
            $profile['other'][$key] =  htmlspecialchars(trim($val)); //防止用户输入javascript代码
        }
    }
    /* 修改在其他资料 */
    if (!empty($profile['other'])){
        $CommonModel->autoExecute('users', $profile['other'], 'UPDATE', "user_id = '$profile[user_id]'");
    }
    $result['msg']		=	'修改成功';
    $result['status']	=	true;
    return $result;
}


/**
 * 取得用户信息
 * @param   int     $user_id    用户id
 * @return  array   用户信息
 */
function user_info($user_id){
	
	$CommonModel	=	new CommonModel();
	
    $sql 			= 	"SELECT * FROM " . 'ybr_users' . " WHERE user_id = '$user_id'";
    $user 			= 	$CommonModel->getRow($sql);
    unset($user['question']);
    unset($user['answer']);

    /* 格式化帐户余额 */
    if ($user){
        $user['formated_user_money'] 	= 	price_format($user['user_money'], false);
        $user['formated_frozen_money'] 	= 	price_format($user['frozen_money'], false);
    }
    return $user;
}


/**
 * 取消一个用户订单
 *
 * @access  public
 * @param   int         $order_id       订单ID
 * @param   int         $user_id        用户ID
 *
 * @return void
 */
function cancel_order($order_id, $user_id = 0){
	
	$CommonModel	=	new CommonModel();
	
	$result			=	array(
		'msg'=>''
	);
	
    /* 查询订单信息，检查状态 */
    $sql 			= 	"SELECT user_id, order_id, order_sn , surplus , integral , bonus_id, order_status, shipping_status, pay_status FROM " . 'ybr_order_info' ." WHERE order_id = '$order_id'";
    $order 			= 	$CommonModel->GetRow($sql);

    if (empty($order)){
        $result['msg']		=	$GLOBALS['_LANG']['order_exist'];
        return false;
    }

    // 如果用户ID大于0，检查订单是否属于该用户
    if ($user_id > 0 && $order['user_id'] != $user_id){
        $result['msg']		=	$GLOBALS['_LANG']['no_priv'];        
        return false;
    }

    // 订单状态只能是“未确认”或“已确认”
    if ($order['order_status'] != OS_UNCONFIRMED && $order['order_status'] != OS_CONFIRMED){    	
        $result['msg']		=	$GLOBALS['_LANG']['current_os_not_unconfirmed'];
        return false;
    }

    //订单一旦确认，不允许用户取消
    if ( $order['order_status'] == OS_CONFIRMED){
		$result['msg']		=	$GLOBALS['_LANG']['current_os_already_confirmed'];
        return false;
    }

    // 发货状态只能是“未发货”
    if ($order['shipping_status'] != SS_UNSHIPPED){
    	$result['msg']		=	$GLOBALS['_LANG']['current_ss_not_cancel'];
        return false;
    }

    // 如果付款状态是“已付款”、“付款中”，不允许取消，要取消和商家联系
    if ($order['pay_status'] != PS_UNPAYED){
		$result['msg']		=	$GLOBALS['_LANG']['current_ps_not_cancel'];
        return false;
    }

    //将用户订单设置为取消
    $sql 			= 	"UPDATE ".'ybr_order_info' ." SET order_status = '".OS_CANCELED."' WHERE order_id = '$order_id'";
        
    if ($CommonModel->execute($sql)){
        /* 记录log */
        order_action($order['order_sn'], OS_CANCELED, $order['shipping_status'], PS_UNPAYED,$GLOBALS['_LANG']['buyer_cancel'],'buyer');
        /* 退货用户余额、积分、红包 */
        if ($order['user_id'] > 0 && $order['surplus'] > 0){
            $change_desc 	= 	sprintf($GLOBALS['_LANG']['return_surplus_on_cancel'], $order['order_sn']);
            log_account_change($order['user_id'], $order['surplus'], 0, 0, 0, $change_desc);
        }
        if ($order['user_id'] > 0 && $order['integral'] > 0){
            $change_desc 	= 	sprintf($GLOBALS['_LANG']['return_integral_on_cancel'], $order['order_sn']);
            log_account_change($order['user_id'], 0, 0, 0, $order['integral'], $change_desc);
        }
        if ($order['user_id'] > 0 && $order['bonus_id'] > 0){
            change_user_bonus($order['bonus_id'], $order['order_id'], false);
        }

        /* 如果使用库存，且下订单时减库存，则增加库存 */
        if ($GLOBALS['_CFG']['use_storage'] == '1' && $GLOBALS['_CFG']['stock_dec_time'] == SDT_PLACE){
            change_order_goods_storage($order['order_id'], false, 1);
        }

        /* 修改订单 */
        $arr = array(
            'bonus_id'  => 0,
            'bonus'     => 0,
            'integral'  => 0,
            'integral_money'    => 0,
            'surplus'   => 0
        );
        update_order($order['order_id'], $arr);

        return true;
    }
    else{
        die($GLOBALS['db']->errorMsg());
    }

}


/**
 * 记录订单操作记录
 *
 * @access  public
 * @param   string  $order_sn           订单编号
 * @param   integer $order_status       订单状态
 * @param   integer $shipping_status    配送状态
 * @param   integer $pay_status         付款状态
 * @param   string  $note               备注
 * @param   string  $username           用户名，用户自己的操作则为 buyer
 * @return  void
 */
function order_action($order_sn, $order_status, $shipping_status, $pay_status, $note = '', $username = null, $place = 0){
    if (is_null($username)){
        $username = $_SESSION['admin_name'];
    }
    $sql = 'INSERT INTO ' . 'ybr_order_action' .
                ' (order_id, action_user, order_status, shipping_status, pay_status, action_place, action_note, log_time) ' .
            'SELECT ' .
                "order_id, '$username', '$order_status', '$shipping_status', '$pay_status', '$place', '$note', '" .gmtime() . "' " .
            'FROM ' . 'ybr_order_info' . " WHERE order_sn = '$order_sn'";
    M()->query($sql);
}


/**
 * 处理红包（下订单时设为使用，取消（无效，退货）订单时设为未使用
 * @param   int     $bonus_id   红包编号
 * @param   int     $order_id   订单号
 * @param   int     $is_used    是否使用了
 */
function change_user_bonus($bonus_id, $order_id, $is_used = true){
	
	$CommonModel	=	new CommonModel();
	
    if ($is_used){
        $sql 		= 	'UPDATE ' . 'ybr_user_bonus' . ' SET ' .
		                'used_time = ' . gmtime() . ', ' .
		                "order_id = '$order_id' " .
		                "WHERE bonus_id = '$bonus_id'";
    }
    else{
        $sql 		= 	'UPDATE ' . 'ybr_user_bonus' . ' SET ' .
		                'used_time = 0, ' .
		                'order_id = 0 ' .
		                "WHERE bonus_id = '$bonus_id'";
    }
    $CommonModel->query($sql);
}


/**
 * 修改订单
 * @param   int     $order_id   订单id
 * @param   array   $order      key => value
 * @return  bool
 */
function update_order($order_id, $order){
	$CommonModel	=	new CommonModel();    
    return $CommonModel->autoExecute('order_info',$order, 'UPDATE', "order_id = '$order_id'");
}


/**
 *  获取指订单的详情
 *
 * @access  public
 * @param   int         $order_id       订单ID
 * @param   int         $user_id        用户ID
 *
 * @return   arr        $order          订单所有信息的数组
 */
function get_order_detail($order_id, $user_id = 0){
	
	$CommonModel		=	new CommonModel();
	
    $order_id 			= 	intval($order_id);
    	
    if ($order_id <= 0){
        //$GLOBALS['err']->add($GLOBALS['_LANG']['invalid_order_id']);
        die($GLOBALS['_LANG']['invalid_order_id']);	
        return false;
    }
    $order 				= 	order_info($order_id);

    //检查订单是否属于该用户
    if ($user_id > 0 && $user_id != $order['user_id']){
        //$GLOBALS['err']->add($GLOBALS['_LANG']['no_priv']);
        die($GLOBALS['_LANG']['no_priv']);
        return false;
    }

    /* 对发货号处理 */
    if (!empty($order['invoice_no'])){
        $shipping_code 				= 	$CommonModel->GetOne("SELECT shipping_code FROM " . ' ybr_shipping ' . " WHERE shipping_id = '$order[shipping_id]'");
       
	    Vendor('Shipping.' . $shipping_code);
		if(class_exists($shipping_code)){
			$shipping 				= 	new $shipping_code;
			$order['invoice_no'] 	= 	$shipping->query($order['invoice_no']);
		}
    }
    
    /* 只有未确认才允许用户修改订单地址 */
    if ($order['order_status'] == OS_UNCONFIRMED){
        $order['allow_update_address'] 	= 	1; //允许修改收货地址
    }
    else{
        $order['allow_update_address'] 	= 	0;
    }

    
    /* 获取订单中实体商品数量 */
    $order['exist_real_goods'] 			= 	exist_real_goods($order_id);

    /* 如果是未付款状态，生成支付按钮 */
    if ($order['pay_status'] == PS_UNPAYED &&
        ($order['order_status'] == OS_UNCONFIRMED ||
        $order['order_status'] == OS_CONFIRMED))
    {
        /*
         * 在线支付按钮
         */
        //支付方式信息
        $payment_info 					= 	array();
        $payment_info					= 	payment_info($order['pay_id']);
		    
        //无效支付方式
        if ($payment_info === false){
            $order['pay_online'] 		= 	'';
        }
        else{
            //取得支付信息，生成支付代码
//            $payment 					= 	unserialize_config($payment_info['pay_config']);
//            
//            //获取需要支付的log_id
//            $order['log_id']    		= 	get_paylog_id($order['order_id'], $pay_type = PAY_ORDER);
//            $order['user_name'] 		= 	$_SESSION['user_name'];
//            $order['pay_desc']  		= 	$payment_info['pay_desc'];
//
//            /* 调用相应的支付方式文件 */
//            vendor('Payment.' . $payment_info['pay_code']);
//            /* 取得在线支付方式的支付按钮 */
//            $pay_obj    				= 	new $payment_info['pay_code'];
//            $order['pay_online'] 		= 	$pay_obj->get_code($order, $payment);
            
        }
    }
    else{
        $order['pay_online'] 			= 	'';
    }
    

    /* 无配送时的处理 */
    $order['shipping_id'] 				== -1 and $order['shipping_name'] = $GLOBALS['_LANG']['shipping_not_need'];

    /* 其他信息初始化 */
    $order['how_oos_name']     			= 	$order['how_oos'];
    $order['how_surplus_name'] 			= 	$order['how_surplus'];

    /* 虚拟商品付款后处理 */
    if ($order['pay_status'] != PS_UNPAYED){
        /* 取得已发货的虚拟商品信息 */
        $virtual_goods 					= 	get_virtual_goods($order_id, true);
        $virtual_card 					= 	array();
        foreach ($virtual_goods AS $code => $goods_list){
            /* 只处理虚拟卡 */
            if ($code == 'virtual_card'){
                foreach ($goods_list as $goods){
                    if ($info = virtual_card_result($order['order_sn'], $goods)){
                        $virtual_card[] = 	array('goods_id'=>$goods['goods_id'], 'goods_name'=>$goods['goods_name'], 'info'=>$info);
                    }
                }
            }
            /* 处理超值礼包里面的虚拟卡 */
            if ($code == 'package_buy'){
                foreach ($goods_list as $goods){
                    $sql 				= 	'SELECT g.goods_id FROM ' . 'ybr_package_goods' . ' AS pg, ' . ' ybr_goods ' . ' AS g ' .
                           					"WHERE pg.goods_id = g.goods_id AND pg.package_id = '" . $goods['goods_id'] . "' AND extension_code = 'virtual_card'";
                    $vcard_arr 			= 	$CommonModel->query($sql);

                    foreach ($vcard_arr AS $val){
                        if ($info = virtual_card_result($order['order_sn'], $val)){
                            $virtual_card[] 	= 	array('goods_id'=>$goods['goods_id'], 'goods_name'=>$goods['goods_name'], 'info'=>$info);
                        }
                    }
                }
            }
        }
        $var_card 						= 	deleteRepeat($virtual_card);
        // 跨模块调用控制器：还没处理完
        //$UserAction						=	new UserAction();
        //$UserAction->assign('virtual_card', $var_card);
    }

    /* 确认时间 支付时间 发货时间 */
    if ($order['confirm_time'] > 0 && ($order['order_status'] == OS_CONFIRMED || $order['order_status'] == OS_SPLITED || $order['order_status'] == OS_SPLITING_PART)){
        $order['confirm_time'] 			= 	sprintf($GLOBALS['_LANG']['confirm_time'], local_date($GLOBALS['_CFG']['time_format'], $order['confirm_time']));
    }
    else{
        $order['confirm_time'] = '';
    }
    if ($order['pay_time'] > 0 && $order['pay_status'] != PS_UNPAYED){
        $order['pay_time'] 				= 	sprintf($GLOBALS['_LANG']['pay_time'], local_date($GLOBALS['_CFG']['time_format'], $order['pay_time']));
    }
    else{
        $order['pay_time'] = '';
    }
    if ($order['shipping_time'] > 0 && in_array($order['shipping_status'], array(SS_SHIPPED, SS_RECEIVED))){
        $order['shipping_time'] 		= 	sprintf($GLOBALS['_LANG']['shipping_time'], local_date($GLOBALS['_CFG']['time_format'], $order['shipping_time']));
    }
    else{
        $order['shipping_time'] 		= 	'';
    }
    return $order;
}



/**
 * 取得订单信息
 * @param   int     $order_id   订单id（如果order_id > 0 就按id查，否则按sn查）
 * @param   string  $order_sn   订单号
 * @return  array   订单信息（金额都有相应格式化的字段，前缀是formated_）
 */
function order_info($order_id, $order_sn = ''){
	$CommonModel	=	new CommonModel();
    /* 计算订单各种费用之和的语句 */
    $total_fee 	= 	" (goods_amount - discount + tax + shipping_fee + insure_fee + pay_fee + pack_fee + card_fee) AS total_fee ";
    $order_id 	= 	intval($order_id);
    if ($order_id > 0){
        $sql 	= 	"SELECT *, " . $total_fee . " FROM " . 'ybr_order_info' .
                	" WHERE order_id = '$order_id'";
    }
    else{
        $sql	= 	"SELECT *, " . $total_fee . "  FROM " . 'ybr_order_info' .
                	" WHERE order_sn = '$order_sn'";
    }
    // 测试
    //echo  $sql;
    
    $order 		= 	$CommonModel->getRow($sql);

    /* 格式化金额字段 */
    if ($order){
        $order['formated_goods_amount']   = price_format($order['goods_amount'], false);
        $order['formated_discount']       = price_format($order['discount'], false);
        $order['formated_tax']            = price_format($order['tax'], false);
        $order['formated_shipping_fee']   = price_format($order['shipping_fee'], false);
        $order['formated_insure_fee']     = price_format($order['insure_fee'], false);
        $order['formated_pay_fee']        = price_format($order['pay_fee'], false);
        $order['formated_pack_fee']       = price_format($order['pack_fee'], false);
        $order['formated_card_fee']       = price_format($order['card_fee'], false);
        $order['formated_total_fee']      = price_format($order['total_fee'], false);
        $order['formated_money_paid']     = price_format($order['money_paid'], false);
        $order['formated_bonus']          = price_format($order['bonus'], false);
        $order['formated_integral_money'] = price_format($order['integral_money'], false);
        $order['formated_surplus']        = price_format($order['surplus'], false);
        $order['formated_order_amount']   = price_format(abs($order['order_amount']), false);
        $order['formated_add_time']       = local_date($GLOBALS['_CFG']['time_format'], $order['add_time']);
    }
    return $order;
}

/**
 * 取得上次未支付的pay_lig_id
 *
 * @access  public
 * @param   array     $surplus_id  余额记录的ID
 * @param   array     $pay_type    支付的类型：预付款/订单支付
 *
 * @return  int
 */
function get_paylog_id($surplus_id, $pay_type = PAY_SURPLUS){
	$CommonModel	=	new CommonModel();
    $sql			= 	'SELECT log_id FROM ' . ' ybr_pay_log ' . " WHERE order_id = '$surplus_id' AND order_type = '$pay_type' AND is_paid = 0";
    return $CommonModel->getOne($sql);
}


/**
 * 返回订单中的虚拟商品
 *
 * @access  public
 * @param   int   $order_id   订单id值
 * @param   bool  $shipping   是否已经发货
 *
 * @return array()
 */
function get_virtual_goods($order_id, $shipping = false){
    if ($shipping){
        $sql 		= 	'SELECT goods_id, goods_name, send_number AS num, extension_code FROM '.
			            ' ybr_order_goods ' .
			            " WHERE order_id = '$order_id' AND extension_code > ''";
    }
    else{
        $sql 		= 	'SELECT goods_id, goods_name, (goods_number - send_number) AS num, extension_code FROM '.
			           	' ybr_order_goods ' .
			           	" WHERE order_id = '$order_id' AND is_real = 0 AND (goods_number - send_number) > 0 AND extension_code > '' ";
    }
    $res 			= 	M()->query($sql);

    $virtual_goods = array();
    foreach ($res AS $row){
        $virtual_goods[$row['extension_code']][] = array('goods_id' => $row['goods_id'], 'goods_name' => $row['goods_name'], 'num' => $row['num']);
    }

    return $virtual_goods;
}


/**
  * 去除虚拟卡中重复数据
  *
  *
  */
function deleteRepeat($array){
    $_card_sn_record 		= 	array();
    foreach ($array as $_k => $_v){
        foreach ($_v['info'] as $__k => $__v){
            if (in_array($__v['card_sn'],$_card_sn_record)){
                unset($array[$_k]['info'][$__k]);
            } else {
                array_push($_card_sn_record,$__v['card_sn']);
            }
        }
    }
    return $array;
}

/**
 * 取得订单商品
 * @param   int     $order_id   订单id
 * @return  array   订单商品数组
 */
function order_goods($order_id){
    $sql 	= 	"SELECT rec_id, goods_id, goods_name, goods_sn, market_price, goods_number, " .
            	"goods_price, goods_attr, is_real, parent_id, is_gift, " .
            	"goods_price * goods_number AS subtotal, extension_code " .
            	"FROM " . 'ybr_order_goods' .
            	" WHERE order_id = '$order_id'";

    $res 	= 	M()->query($sql);
    /* 不理会商品礼包
	foreach($res as $row){
		if ($row['extension_code'] == 'package_buy'){
            $row['package_goods_list'] 	= 	get_package_goods($row['goods_id']);
        }
        $goods_list[] 					= 	$row;
	}
	*/
    $goods_list		=	$res;    
    return $goods_list;
}

/**
 *  添加或更新指定用户收货地址
 *
 * @access  public
 * @param   array       $address
 * @return  bool
 */
function update_address($address){
	
	$CommonModel		=	new CommonModel();	
    $address_id 		= 	intval($address['address_id']);
    unset($address['address_id']);

    if ($address_id > 0){
        /* 更新指定记录 */
        $CommonModel->autoExecute('user_address', $address, 'UPDATE', 'address_id = ' .$address_id . ' AND user_id = ' . $address['user_id']);
    }
    else{
        /* 插入一条新记录 */
        $CommonModel->autoExecute( 'user_address' , $address, 'INSERT');
        $address_id 	= 	$CommonModel->insert_id();
    }

    if (isset($address['default']) && $address['default'] > 0 && isset($address['user_id'])){
        $sql 			= 	"UPDATE " . 'ybr_users' .
			                " SET address_id = '".$address_id."' ".
			                " WHERE user_id = '" .$address['user_id']. "'";
        $CommonModel->execute($sql);
    }
    return true;
}

/**
 *  将一个字串中含有全角的数字字符、字母、空格或'%+-()'字符转换为相应半角字符
 *
 * @access  public
 * @param   string       $str         待转换字串
 *
 * @return  string       $str         处理后字串
 */
function make_semiangle($str){
    $arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
                 '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
                 'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
                 'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
                 'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
                 'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
                 'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
                 'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
                 'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
                 'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
                 'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
                 'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
                 'ｙ' => 'y', 'ｚ' => 'z',
                 '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
                 '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
                 '‘' => '[', '’' => ']', '｛' => '{', '｝' => '}', '《' => '<',
                 '》' => '>',
                 '％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
                 '：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',
                 '；' => ',', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',
                 '”' => '"', '’' => '`', '‘' => '`', '｜' => '|', '〃' => '"',
                 '　' => ' ');
    return strtr($str, $arr);
}


/**
 * 删除一个收货地址
 *
 * @access  public
 * @param   integer $id
 * @return  boolean
 */
function drop_consignee($id){
	
	$CommonModel	=	new CommonModel();
	
    $sql 			= 	"SELECT user_id FROM " . 'ybr_user_address' . " WHERE address_id = '$id'";
    $uid 			= 	$CommonModel->getOne($sql);

    if ($uid != $_SESSION['user_id']){
        return false;
    }
    else{
        $sql 		= 	"DELETE FROM " . 'ybr_user_address' . " WHERE address_id = '$id'";
        $res 		= 	$CommonModel->execute($sql);
        return $res;
    }
}


/**
 *  添加留言函数
 *
 * @access  public
 * @param   array       $message
 *
 * @return  boolen      $bool
 */
function add_message($message){
	
	$CommonModel				=	new CommonModel();
	
    $upload_size_limit 			= 	$GLOBALS['_CFG']['upload_size_limit'] == '-1' ? ini_get('upload_max_filesize') : $GLOBALS['_CFG']['upload_size_limit'];
    $status 					= 	1 - $GLOBALS['_CFG']['message_check'];

    $last_char 					= 	strtolower($upload_size_limit{strlen($upload_size_limit)-1});

    switch ($last_char){
        case 'm':
            $upload_size_limit 	*= 	1024*1024;
            break;
        case 'k':
            $upload_size_limit 	*= 	1024;
            break;
    }

    if ($message['upload']){
        if($_FILES['message_img']['size'] / 1024 > $upload_size_limit){
            //$GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['upload_file_limit'], $upload_size_limit));
            return false;
        }
        // 暂时关闭留言中上传图片
        //$img_name 				= 	upload_file($_FILES['message_img'], 'feedbackimg');

        if ($img_name === false){
            return false;
        }
    }
    else{
        $img_name 				= 	'';
    }

    if (empty($message['msg_title'])){
        //$GLOBALS['err']->add($GLOBALS['_LANG']['msg_title_empty']);
        return false;
    }

    $message['msg_area'] 		= 	isset($message['msg_area']) ? intval($message['msg_area']) : 0;
    $sql 						= 	"INSERT INTO " . 'ybr_feedback' .
						            " (msg_id, parent_id, user_id, user_name, user_email, msg_title, msg_type, msg_status,  msg_content, msg_time, message_img, order_id, msg_area)".
						            " VALUES (NULL, 0, '$message[user_id]', '$message[user_name]', '$message[user_email]', ".
						            " '$message[msg_title]', '$message[msg_type]', '$status', '$message[msg_content]', '".gmtime()."', '$img_name', '$message[order_id]', '$message[msg_area]')";
    $CommonModel->query($sql);
    return true;
}

/**
 * 判断用户是否已注册
 * Enter description here ...
 */
function is_user_exists($username = ''){
	$CommonModel	=	new CommonModel();
	$datas			=	$CommonModel->getRow(" select count(*) count from ybr_users where user_name ='$username' limit 1 ");
	if(empty($datas['count'])){
		return false;
	}
	else{
		return true;
	}
}

















